package com.bs.bszhsq.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bs.bszhsq.dto.UsersDTO;
import com.bs.bszhsq.entity.*;
import com.bs.bszhsq.exception.ServiceException;
import com.bs.bszhsq.mapper.RoleMenuMapper;
import com.bs.bszhsq.mapper.UsersMapper;
import com.bs.bszhsq.service.IMenuService;
import com.bs.bszhsq.service.IRoleService;
import com.bs.bszhsq.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.bszhsq.utils.MessageType;
import com.bs.bszhsq.utils.R;
import com.bs.bszhsq.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 章宇光
 * @since 2024-03-17
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    private static final Log LOG= Log.get();

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IRoleService roleService;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private IMenuService menuService;
    @Override
    public UsersDTO login(UsersDTO usersDTO) {
        // todo 密码加密
//        SymmetricCrypto ase = new SymmetricCrypto("ASE");
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", usersDTO.getUsername());
        queryWrapper.eq("password", usersDTO.getPassword());
        queryWrapper.eq("role", usersDTO.getRole());
        // 不能存在相同的账号密码
        Users one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException("500", "服务开小差!");
        }
        if (one != null) {
            BeanUtil.copyProperties(one, usersDTO, true);
            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword());
            usersDTO.setToken(token);
            try {
                stringRedisTemplate.opsForValue().increment(MessageType.LOGIN_NUM.getName(),1);
            } catch (Exception e) {
                throw new ServiceException("500","服务出小差了~");
            }
            String role = one.getRole();
            LambdaQueryWrapper<Role> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Role::getFlag,role);
            Role one1 = roleService.getOne(lqw);
            LambdaQueryWrapper<RoleMenu> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(RoleMenu::getRoleId,one1.getId());
            List<RoleMenu> roleMenus = roleMenuMapper.selectList(lqw2);
            List<Integer> menuId = CollUtil.getFieldValues(roleMenus, "menuId", Integer.class);
            LambdaQueryWrapper<Menu> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Menu::getId,menuId);
            List<Menu> list = menuService.list(lambdaQueryWrapper);
            List<Menu> parentNode = list.stream().filter(menu -> menu.getPid()== 0).collect(Collectors.toList());
            for (Menu menu : parentNode) {
                List<Menu> collect = list.stream().filter(menu1 -> menu.getId().equals(menu1.getPid())).collect(Collectors.toList());
                menu.setChildren(collect);
            }
            usersDTO.setMenus(parentNode);
            return usersDTO;
        } else {
            throw new ServiceException("500", "用户名或者密码错误！");
        }
    }

    @Override
    public boolean saveUser(UsersDTO usersDTO) {
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",usersDTO.getUsername());
        Users one;
        try {
            one= this.getOne(queryWrapper);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException("500","服务开小差！");
        }
      if (one!=null){
          throw new ServiceException("500","用户名已经存在");
      }else {
          Users users = BeanUtil.copyProperties(usersDTO, Users.class);
          users.setAddtime(LocalDateTime.now());
          this.save(users);
      }
      return true;
    }

    @Override
    public List<Echarts> selectWeekLookCount(List<String> sevenDate) {
        return usersMapper.getNumbers(sevenDate);

    }

    @Override
    public List<EchartsRoles> getRoles() {
       return usersMapper.getRoles();

    }


}
